package com.ecut.drug_bid.controller;

import com.ecut.drug_bid.domain.Tender;
import com.ecut.drug_bid.dto.TenderCreateRequest;
import com.ecut.drug_bid.service.TenderService;
import com.ecut.drug_bid.util.UserContext;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/tenders")
@RequiredArgsConstructor
public class TenderController {
    private final TenderService tenderService;

    // 查询所有招标信息（所有人可见）
    @GetMapping
    public ResponseEntity<List<Tender>> list() {
        return ResponseEntity.ok(tenderService.findAll());
    }

    // 根据编号查询（所有人可见）
    @GetMapping("/{tenderCode}")
    public ResponseEntity<Tender> getByCode(@PathVariable(name = "tenderCode") String tenderCode) {
        return tenderService.findByCode(tenderCode)
            .map(ResponseEntity::ok)
            .orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 创建招标（需要登录，招标单位或管理员）
    @PostMapping
    public ResponseEntity<Tender> create(@Valid @RequestBody TenderCreateRequest request) {
        Long userId = UserContext.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.status(401).build();
        }
        Tender tender = tenderService.create(request, userId);
        return ResponseEntity.ok(tender);
    }

    // 更新招标（需要登录，招标单位或管理员）
    @PutMapping("/{tenderCode}")
    public ResponseEntity<Tender> update(
        @PathVariable(name = "tenderCode") String tenderCode,
        @Valid @RequestBody TenderCreateRequest request
    ) {
        Long userId = UserContext.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.status(401).build();
        }
        Tender tender = tenderService.update(tenderCode, request, userId);
        return ResponseEntity.ok(tender);
    }

    // 删除招标（仅管理员）
    @DeleteMapping("/{tenderCode}")
    public ResponseEntity<Void> delete(@PathVariable(name = "tenderCode") String tenderCode) {
        String userType = UserContext.getCurrentUserType();
        if (!"ADMIN".equals(userType)) {
            return ResponseEntity.status(403).build();
        }
        tenderService.delete(tenderCode);
        return ResponseEntity.noContent().build();
    }
}